package com.pansoft.kline.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.frame.baseui.BaseLazyFragment;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.kline.activity.TransactionTrendActivity;
import com.pansoft.kline.adapter.KlineOptionalOrMVAdapter;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.helper.BtcKanConfigAndRateHelper;
import com.pansoft.kline.model.BourseSecondPageModel;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.pansoft.kline.model.KlineOptionalOrMVModel;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.constant.MarketConstant;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.TCMathUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/12/3 11:21
 * @desc : 交易所二级页面的fragment
 * @version: 1.0
 */
public class BourseSecondPageFragment extends BaseLazyFragment {

    private String siteName, currency;
    private RecyclerView recycler;
    private SmartRefreshLayout refreshLayout;
    private KlineOptionalOrMVAdapter adapter;
    private List<KlineOptionalOrMVModel> klineOptionalOrMVModels = new ArrayList<>();
    private List<BourseSecondPageModel.DataBean.TickersBean> lastTickersBeans = new ArrayList<>();
    private int page = 1;
    private int page_size = 20;
    //当前货币code 如CNY USD
    private String currencyCode;

    public static BourseSecondPageFragment newInstance(String siteName, String currency) {

        Bundle args = new Bundle();
        args.putString("siteName", siteName);
        args.putString("currency", currency);
        BourseSecondPageFragment fragment = new BourseSecondPageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.kline_fragment_bourse_second_page, null);
        if (getArguments() != null) {
            siteName = getArguments().getString("siteName");
            currency = getArguments().getString("currency");
        }
        initView(root);
        initListener();
        return root;
    }


    private void initListener() {
        /**
         * 列表点击事件
         */
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TransactionTrendActivity.start(_mActivity, klineOptionalOrMVModels.get(position).getMarketId());
            }
        });
        /**
         * 刷新加载
         */
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                requestData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                requestData();
            }
        });
    }

    private void initView(View root) {
        recycler = root.findViewById(R.id.recycler);
        refreshLayout = root.findViewById(R.id.refreshLayout);
        recycler.setLayoutManager(new LinearLayoutManager(_mActivity));
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(_mActivity, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(_mActivity, R.drawable.kline_shape_recycler_divider));
        recycler.addItemDecoration(divider);
        adapter = new KlineOptionalOrMVAdapter(R.layout.kline_item_optional_or_mv, klineOptionalOrMVModels);
        recycler.setAdapter(adapter);


    }

    /**
     * 第一次初始化时加载此方法 ，以后不会再走
     */
    @Override
    protected void onFirstInit() {
        super.onFirstInit();
        currencyCode = CurrencyAndBourseManager.getCurrencyUnitCode();
        refreshLayout.autoRefresh();
    }

    /**
     * 请求数据
     */
    private void requestData() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("currency", currency);
        hashMap.put("page_size", page_size + "");
        hashMap.put("page", page + "");
        JFCommonRequestManager.getInstance(_mActivity).requestGetByAsyn(TAG, MarketConstant.MARKET_BOURSE_SECOND_PAGE_URL + siteName, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                try {
                    BourseSecondPageModel bourseSecondPageModel = new Gson().fromJson(result, BourseSecondPageModel.class);
                    if (bourseSecondPageModel.getCode() != 0) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        return;
                    }
                    disposeBouSecondPageData(bourseSecondPageModel);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
            }
        });
    }

    /**
     * 处理请求的数据
     *
     * @param bourseSecondPageModel
     */
    private void disposeBouSecondPageData(BourseSecondPageModel bourseSecondPageModel) {
        if (bourseSecondPageModel != null) {

            List<BourseSecondPageModel.DataBean.TickersBean> tickersBeans = bourseSecondPageModel.getData().getTickers();
//            if (lastTickersBeans.size() == 0) {
//                lastTickersBeans.addAll(tickersBeans);
//            }
            if (tickersBeans != null && tickersBeans.size() != 0) {
                //当数据小于page_size时,加载完成，没有更多数据
                if (tickersBeans.size() < page_size) {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
                if (page == 1) {
                    klineOptionalOrMVModels.clear();
                }
                for (int i = 0; i < tickersBeans.size(); i++) {
                    BourseSecondPageModel.DataBean.TickersBean tickersBean = tickersBeans.get(i);
//                    BourseSecondPageModel.DataBean.TickersBean lastTickersBean = lastTickersBeans.get(i);
                    KlineOptionalOrMVModel klineOptionalOrMVModel = new KlineOptionalOrMVModel();
                    //根据marketId查找币的名字
                    ConfigMarketBean configMarketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(tickersBeans.get(i).getId());
                    klineOptionalOrMVModel.setMarketId(tickersBean.getId());
                    klineOptionalOrMVModel.setName(configMarketBean.getCoin());
                    //查找对应的信息
//                            ConfigCoinBean configCoinBean = DaoMaster.getDaoSessionInstance().getConfigCoinBeanDao().load(listBeans.get(j).getTitle());
//                LogUtils.e("获取到的币的信息---ConfigMarketBean-》" + configMarketBean.getCoin() + "----" + configMarketBean.getSite() +
//                        "---->" + configMarketBean.getCurrency() + "-----" + configMarketBean.getType());

                    //根据查到的site查找site的title
                    ConfigSiteBean configSiteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(configMarketBean.getSite());
//                LogUtils.e("获取到的币的信息---configSiteBean-》" + configSiteBean.getTitle() + "----" + configSiteBean.getFee() +
//                        "---->" + configSiteBean.getUrl() + "-----" + configSiteBean.getUniqueKey());
                    //根据查到的coin获取coins
                    ConfigCoinBean configCoinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(configMarketBean.getCoin());
//                LogUtils.e("获取到的币的信息---configCoinBean-》" + configCoinBean.getTitle() + "----" + configCoinBean.getName() +
//                        "---->" + configCoinBean.getCoin_name_other() + "-----" + configCoinBean.getSymbol());
                    String future = "";
                    //获取future
                    if (configMarketBean.getFuture() != null && !configMarketBean.getFuture().equals("")) {
                        future = DaoSessionUtil.getInstance().getConfigFutureBeanDao().load(configMarketBean.getFuture()).getTitle();
                    }
                    JSONObject rateObject = BtcKanConfigAndRateHelper.getRate(null);
                    String rate = null;
                    try {
                        rate = rateObject.getJSONObject(configMarketBean.getSite()).getString(configMarketBean.getCurrency());
                        String rateRmb = rateObject.getJSONObject(configMarketBean.getSite()).getString(currencyCode);
                        double value = TCMathUtil.mul((tickersBean.getLast() / Double.valueOf(rate)) + "", rateRmb);
                        klineOptionalOrMVModel.setTitle(configSiteBean.getTitle() + future + "," + configCoinBean.getTitle());
                        klineOptionalOrMVModel.setPrice(CurrencyAndBourseManager.getNowCurrencySymbol() + value);

                        //将double数据转换为正常数据显示  不适用科学计数法  new BigDecimal(tickersBean.getLast()+"").toPlainString()
                        klineOptionalOrMVModel.setSubPrice(KLineUtil.getCurrencySymbol(configMarketBean.getCurrency()) + new BigDecimal(tickersBean.getLast() + "").toPlainString() + "");
//                    klineOptionalOrMVModel.setNum(configMarketBean.getCurrency() + " 量 " + conversion(tickersBeans.get(i).getVol() + "", CONVERSION_UNIT_VALUE_TEN_SHOUSAND, CONVERSION_UNIT_VALUE_POINT) + "万");
                        klineOptionalOrMVModel.setNum(configMarketBean.getCurrency() + " "+ResStringUtil.getString(R.string.chart_kline_detail_volume)+" " +
                                MarketNumberUtils.amountConversion(tickersBean.getVol()));
                        //计算涨跌幅的百分比   （last-open）/open*100
                        double changeRate = (tickersBean.getLast() - tickersBean.getOpen()) / tickersBean.getOpen() * 100;
                        //如果大于0涨  小于0跌
                        if (changeRate > 0) {
                            klineOptionalOrMVModel.setIncrease(true);
                            klineOptionalOrMVModel.setChangeRate("+" + KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                        } else {
                            klineOptionalOrMVModel.setIncrease(false);
                            klineOptionalOrMVModel.setChangeRate(KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                        }
//                        if (tickersBean.getLast() > lastTickersBean.getLast()) {
//                            klineOptionalOrMVModel.setTrendType(1);
//                            tickersBean.setLastTrendType(1);
//                        } else if (lastTickersBean.getLast() > tickersBean.getLast()) {
//                            klineOptionalOrMVModel.setTrendType(-1);
//                            tickersBean.setLastTrendType(-1);
//                        } else {
//                            klineOptionalOrMVModel.setTrendType(lastTickersBean.getLastTrendType());
//                            tickersBean.setLastTrendType(lastTickersBean.getLastTrendType());
//                        }
                        klineOptionalOrMVModels.add(klineOptionalOrMVModel);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                lastTickersBeans.clear();
                lastTickersBeans.addAll(tickersBeans);
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void DestroyView() {

    }

    /**
     * 在ViewPager中切换fragment时，当前fragment显示时走此方法
     */
    @Override
    protected void onUserVisible() {
        refreshLayout.autoRefresh();
    }

    /**
     * 在ViewPager中切换fragment时，当前fragment不显示时走此方法
     */
    @Override
    protected void onUserInvisible() {

    }
}
